package hammersmith.local.ui.gui;

import hammersmith.local.exceptions.ArticleNotFoundException;
import hammersmith.local.management.ShopManagement;
import hammersmith.local.valueobjects.Article;
import hammersmith.local.valueobjects.CustomTableRenderer;
import hammersmith.local.valueobjects.Employee;
import hammersmith.local.valueobjects.MassArticle;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

public class EmployeeMask extends JFrame {

	ShopManagement shop;
	Employee employee;
	private static final long serialVersionUID = 1L;
	private JTable table;
	private JPanel panel;
	private JPanel pnlHeader;
	private JPanel pnlLeft;
	private JPanel pnlContent;
	private JPanel pnlRight;
	private JPanel pnlBottom;

	public EmployeeMask(final ShopManagement shop, final Employee employee) {
		getContentPane().setBackground(Color.WHITE);
		this.shop = shop;
		this.employee = employee;

		getContentPane().setLayout(null);

		this.setSize(872, 694);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		panel = new JPanel();
		panel.setBounds(6, 6, 840, 638);
		getContentPane().add(panel);
		panel.setLayout(new BorderLayout(0, 0));

		pnlContent = new JPanel();
		pnlContent.setAlignmentY(Component.BOTTOM_ALIGNMENT);
		pnlContent.setBackground(Color.WHITE);
		panel.add(pnlContent, BorderLayout.CENTER);

		renderPanelHeader();
		renderPanelLeft();
		renderPanelRight();
		renderPanelBottom();
		
		this.setVisible(true);
	}

	private void renderPanelHeader() {
		pnlHeader = new JPanel();
		pnlHeader.setBackground(Color.WHITE);
		pnlHeader.setBorder(BorderFactory.createLineBorder(Color.black));
		panel.add(pnlHeader, BorderLayout.NORTH);

		JLabel lblPlaceholderLogo = new JLabel("");
		lblPlaceholderLogo.setIcon(new ImageIcon("img/logo.png"));
		pnlHeader.add(lblPlaceholderLogo);
	}

	private void renderPanelLeft() {

		pnlLeft = new JPanel();
		pnlLeft.setBackground(Color.WHITE);
		panel.add(pnlLeft, BorderLayout.WEST);
		GridBagLayout gbl_pnlLeft = new GridBagLayout();
		gbl_pnlLeft.columnWidths = new int[] { 0, 0 };
		gbl_pnlLeft.rowHeights = new int[] { 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0,
				0, 0, 0, 0 };
		gbl_pnlLeft.columnWeights = new double[] { 0.0, Double.MIN_VALUE };
		gbl_pnlLeft.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
				0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
		pnlLeft.setLayout(gbl_pnlLeft);
		pnlLeft.setBorder(BorderFactory.createLineBorder(Color.black));

		JLabel lblIndex = new JLabel("    News    ");
		lblIndex.setFont(new Font("Lucida Grande", Font.BOLD, 16));
		GridBagConstraints gbc_lblIndex = new GridBagConstraints();
		gbc_lblIndex.insets = new Insets(0, 0, 5, 0);
		gbc_lblIndex.gridx = 0;
		gbc_lblIndex.gridy = 1;
		pnlLeft.add(lblIndex, gbc_lblIndex);

		JLabel lblHauptseite = new JLabel("anlegen");
		GridBagConstraints gbc_lblHauptseite = new GridBagConstraints();
		gbc_lblHauptseite.insets = new Insets(0, 0, 5, 0);
		gbc_lblHauptseite.gridx = 0;
		gbc_lblHauptseite.gridy = 2;
		pnlLeft.add(lblHauptseite, gbc_lblHauptseite);

		JLabel lblBearbeiten = new JLabel("bearbeiten");
		GridBagConstraints gbc_lblBearbeiten = new GridBagConstraints();
		gbc_lblBearbeiten.insets = new Insets(0, 0, 5, 0);
		gbc_lblBearbeiten.gridx = 0;
		gbc_lblBearbeiten.gridy = 3;
		pnlLeft.add(lblBearbeiten, gbc_lblBearbeiten);

		JLabel lblSortiment = new JLabel("    Sortiment    ");
		lblSortiment.setFont(new Font("Lucida Grande", Font.BOLD, 16));
		GridBagConstraints gbc_lblSortiment = new GridBagConstraints();
		gbc_lblSortiment.insets = new Insets(0, 0, 5, 0);
		gbc_lblSortiment.gridx = 0;
		gbc_lblSortiment.gridy = 5;
		pnlLeft.add(lblSortiment, gbc_lblSortiment);

		JLabel lblShowArticle = new JLabel("Artikel anzeigen");
		GridBagConstraints gbc_test = new GridBagConstraints();
		gbc_test.insets = new Insets(0, 0, 5, 0);
		gbc_test.gridx = 0;
		gbc_test.gridy = 6;
		pnlLeft.add(lblShowArticle, gbc_test);
		lblShowArticle.setCursor(new Cursor(Cursor.HAND_CURSOR));

		lblShowArticle.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				showArticles();
				pnlContent.updateUI();
			}
		});

		JLabel lblCreateArticle = new JLabel("Artikel anlegen");
		GridBagConstraints gbc_lblHosen = new GridBagConstraints();
		gbc_lblHosen.anchor = GridBagConstraints.ABOVE_BASELINE;
		gbc_lblHosen.insets = new Insets(0, 0, 5, 0);
		gbc_lblHosen.gridx = 0;
		gbc_lblHosen.gridy = 7;
		pnlLeft.add(lblCreateArticle, gbc_lblHosen);
		lblCreateArticle.setCursor(new Cursor(Cursor.HAND_CURSOR));

		lblCreateArticle.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				new CreateArticleMask(employee, shop);
			}
		});
	}

	private void renderPanelBottom() {
		pnlBottom = new JPanel();
		pnlBottom.setBackground(Color.WHITE);
		panel.add(pnlBottom, BorderLayout.SOUTH);
		pnlBottom.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 5));

		JLabel lblAgb = new JLabel("AGB");
		pnlBottom.add(lblAgb);

		JLabel lblKontakt = new JLabel("Kontakt");
		pnlBottom.add(lblKontakt);

		JLabel lblImpressum = new JLabel("Impressum");
		pnlBottom.add(lblImpressum);
	}

	private void renderPanelRight() {
		pnlRight = new JPanel();
		pnlRight.setBackground(Color.WHITE);
		panel.add(pnlRight, BorderLayout.EAST);
		GridBagLayout gbl_pnlRight = new GridBagLayout();
		gbl_pnlRight.columnWidths = new int[] { 0, 0 };
		gbl_pnlRight.rowHeights = new int[] { 42, 33, 18, 0, 0 };
		gbl_pnlRight.columnWeights = new double[] { 0.0, Double.MIN_VALUE };
		gbl_pnlRight.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0,
				Double.MIN_VALUE };
		pnlRight.setLayout(gbl_pnlRight);
		pnlRight.setBorder(BorderFactory.createLineBorder(Color.black));

		JLabel lblLogout = new JLabel("     Logout     ");
		lblLogout.setVerticalAlignment(SwingConstants.TOP);
		GridBagConstraints gbc_lblLogout = new GridBagConstraints();
		gbc_lblLogout.insets = new Insets(0, 0, 10, 0);
		gbc_lblLogout.gridx = 0;
		gbc_lblLogout.gridy = 0;
		pnlRight.add(lblLogout, gbc_lblLogout);
		lblLogout.setCursor(new Cursor(Cursor.HAND_CURSOR));
		lblLogout.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				dispose();
				new LoginMask();
			}
		});
	}

	private void showArticles() {

		pnlContent.removeAll();
		pnlContent.setLayout(null);
		final JScrollPane scrollPane = new JScrollPane();
		pnlContent.add(scrollPane);
		scrollPane.setBounds(10, 11, 647, 425);

		table = new JTable();
		table.setAutoCreateRowSorter(true);
		
		@SuppressWarnings("serial")
		DefaultTableModel model = new DefaultTableModel() {

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		
		model.addColumn("Art.-Nr.");
		model.addColumn("Typ");
		model.addColumn("Name");
		model.addColumn("Größe");
		model.addColumn("Farbe");
		model.addColumn("Bestand");
		model.addColumn("Preis in €");
		model.addColumn("Losgröße");

		table.setDefaultRenderer(Object.class, new CustomTableRenderer());

		ArrayList<Article> list = shop.getArticleManagement().getArticleList();
		for (Article article : list) {

			if (article instanceof MassArticle) {
				MassArticle articleM = (MassArticle) article;
				model.addRow(new Object[] { String.valueOf(articleM.getId()),
						articleM.getType(), articleM.getName(),
						articleM.getSize(), articleM.getColor(),
						String.valueOf(articleM.getStock()),
						String.valueOf(articleM.getPrice()),
						String.valueOf(articleM.getMinCount()) });

			} else {
				model.addRow(new Object[] { String.valueOf(article.getId()),
						article.getType(), article.getName(),
						article.getSize(), article.getColor(),
						String.valueOf(article.getStock()),
						String.valueOf(article.getPrice()), "1" });
			}

		}

		table.setModel(model);

		table.getColumnModel().getColumn(0).setResizable(false);
		table.getColumnModel().getColumn(0).setPreferredWidth(50);
		table.getColumnModel().getColumn(1).setResizable(false);
		table.getColumnModel().getColumn(1).setPreferredWidth(82);
		table.getColumnModel().getColumn(2).setResizable(false);
		table.getColumnModel().getColumn(2).setPreferredWidth(135);
		table.getColumnModel().getColumn(3).setResizable(false);
		table.getColumnModel().getColumn(3).setPreferredWidth(57);
		table.getColumnModel().getColumn(4).setResizable(false);
		table.getColumnModel().getColumn(4).setPreferredWidth(83);
		table.getColumnModel().getColumn(5).setResizable(false);
		table.getColumnModel().getColumn(5).setPreferredWidth(80);
		table.getColumnModel().getColumn(6).setResizable(false);
		table.getColumnModel().getColumn(6).setPreferredWidth(50);
		table.getColumnModel().getColumn(7).setResizable(false);
		table.getColumnModel().getColumn(7).setPreferredWidth(70);

		scrollPane.setViewportView(table);

		JPanel pnlButtons = new JPanel();
		pnlButtons.setAlignmentY(Component.BOTTOM_ALIGNMENT);
		pnlButtons.setBorder(new LineBorder(new Color(0, 0, 0)));
		pnlButtons.setBounds(10, 441, 647, 35);
		pnlContent.add(pnlButtons);

		JButton btnEdit = new JButton("Bearbeiten");
		btnEdit.setActionCommand("New Command");
		btnEdit.setAlignmentY(Component.TOP_ALIGNMENT);
		pnlButtons.add(btnEdit);
		btnEdit.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				int row = table.getSelectedRow();
				String id = String.valueOf(table.getValueAt(row, 0));

				new EditArticleMask(shop, id, employee);
				
			}
		});

		JButton btnDelete = new JButton("Löschen");
		btnDelete.setAlignmentY(1.0f);
		pnlButtons.add(btnDelete);
		btnDelete.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				int row = table.getSelectedRow();
				String id = String.valueOf(table.getValueAt(row, 0));

				Article article = null;

				try {
					article = shop.getArticleManagement().getArticleById(
							Long.valueOf(id));
				} catch (NumberFormatException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (ArticleNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				int n = JOptionPane.showConfirmDialog(null,
						"Wollen Sie den Artikel " + article.getId() + " ("
								+ article.getName() + ") wirklich löschen?",
						"Löschen?", JOptionPane.YES_NO_OPTION);

				if (n == 0) {
					shop.deleteArticle(employee, article);
				}
			}
		});

		JButton btnStockhistory = new JButton("Bestandshistorie");

		btnStockhistory.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {

				int row = table.getSelectedRow();
				String id = String.valueOf(table.getValueAt(row, 0));

				Article article = null;

				try {
					article = shop.getArticleManagement().getArticleById(
							Long.valueOf(id));

					String input = JOptionPane.showInputDialog("Wieviele Tage zurück?");
					
					int[] logs = shop.getLogger().getLogByArticleAndDays(
							article, Integer.parseInt(input));
					
					JPanel stockChartPanel = new StockChartPanel(article, logs)
							.getPanelView();
					
					JFrame stockChartWindow = new JFrame();
					stockChartWindow.setSize(750, 500);
					stockChartWindow.setLocationRelativeTo(null);
					stockChartWindow.add(stockChartPanel);
					stockChartWindow.validate();
					stockChartWindow.setVisible(true);

				} catch (NumberFormatException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (ArticleNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			}
		});

		pnlButtons.add(btnStockhistory);
	}

}
